from django import http
from django.shortcuts import render
from django.views import View
from django.core.cache import cache

from areas.models import Area
from meiduo_mall.utils.response_code import RETCODE


class AreasView(View):
    #  省级市数据处理
    def get(self, request):
        # 提供省市区数据
        area_id = request.GET.get('area_id')
        if area_id is None:
            # 如果没有值则先先去readis里面看有没有省的值
            province_list = cache.get('province_list')
            if province_list is None: # 如果redis没有就要去mysql
                province_qs = Area.objects.filter(parent=None) # 取到查询集
                province_list = [] # 准备空列表
                for province_model in province_qs: # 遍历查询集将每个模型转化成字典
                    province_list.append({
                        'id': province_model.id,
                        'name': province_model.name
                    })
                cache.set('province_list',province_list, 3600)# 将数据存在redis
            # 如果有直接响应回去
            return http.JsonResponse({'code':RETCODE.OK, 'errmsg': 'OK', 'province_list': province_list})
        else:
            # 有值就写下面的行政区
            # 先读redis
            data_dict = cache.get('sub_area' + area_id)
            # 没有就去mysql查询
            if data_dict is None:
                parent_model = Area.objects.get(id=area_id)
                sub_qs = parent_model.subs.all()
                sub_list = []
                for sub_model in sub_qs:
                    sub_list.append({
                        'id': sub_model.id,
                        'name': sub_model.name
                    })
                    # 包装的东西
                    data_dict = {
                        'id': parent_model.id,
                        'name': parent_model.name,
                        'subs': sub_list
                    }
                cache.set('sub_area' + area_id, data_dict, 3600)
            # 有就直接响应
            return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK', 'sub_data': data_dict})






